/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharePoint404Handler
{
    class ListBased404Handler : SPFeatureReceiver
    {

        private const string specified404Page = "Custom404Page.htm";
        private const string webAppPropertyForGuid = "URLRedirectListGuid";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;
            string urlRedirectListGuid = "";
            
            using (SPSite thisSite = thisWebApp.Sites[0])
            {
                using (SPWeb thisWeb = thisSite.RootWeb)
                {
                    SPListTemplate thisTemplate;
                    try
                    {
                        SPListTemplateCollection siteTemplates = thisSite.GetCustomListTemplates(thisWeb);
                        thisTemplate = siteTemplates["URL Redirect"];
                    }
                    catch (Exception ex)
                    {
                        throw new SPException("Couldn't find the List Template named \"URLRedirect\" in the root web [" + thisWeb.Url + "].  Ensure the \"404 URL Redirect List Template\" feature is activated in this web. Error: [" + ex.Message + "]");
                    }

                    Guid thisListsGuid = new Guid();
                    int x = 0;

                    while (thisListsGuid == Guid.Empty)
                    {
                        string thisListNameAttempt = "URL Redirect";
                        if (x > 0) thisListNameAttempt += " " + x.ToString();
                        x++;
                        try
                        {
                            thisListsGuid = thisWeb.Lists.Add(thisListNameAttempt, "Use this list to define paths to pages that cause 404 errors, and handle them accordingly.", thisTemplate);
                        }
                        catch (SPException ex)
                        {
                            if (x > 10) throw new SPException("More than 10 attempts to create the \"" + thisListNameAttempt + "\" list failed (try cleaning up previously created URL Redirect lists): " + ex.Message);
                        }
                    }
                    urlRedirectListGuid = thisListsGuid.ToString();
                }

            }

            if (thisWebApp.Properties.ContainsKey("PreviousFileNotFoundPageSetting")) 
                thisWebApp.Properties["PreviousFileNotFoundPageSetting"] = thisWebApp.FileNotFoundPage; 
            else 
                thisWebApp.Properties.Add("PreviousFileNotFoundPageSetting", thisWebApp.FileNotFoundPage);

            thisWebApp.FileNotFoundPage = specified404Page;

            if (thisWebApp.Properties.ContainsKey("Custom404Path")) 
                thisWebApp.Properties["Custom404Path"] = specified404Page; 
            else 
                thisWebApp.Properties.Add("Custom404Path", specified404Page);
            if (urlRedirectListGuid != "") 
                if (thisWebApp.Properties.ContainsKey(webAppPropertyForGuid)) 
                    thisWebApp.Properties[webAppPropertyForGuid] = urlRedirectListGuid; 
                else 
                    thisWebApp.Properties.Add(webAppPropertyForGuid, urlRedirectListGuid);

            
            thisWebApp.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;

            if (thisWebApp.Properties.ContainsKey("PreviousFileNotFoundPageSetting"))
            {
                thisWebApp.FileNotFoundPage = thisWebApp.Properties["PreviousFileNotFoundPageSetting"].ToString();
                thisWebApp.Properties.Remove("PreviousFileNotFoundPageSetting");
            }
            if (thisWebApp.Properties.ContainsKey("Custom404Path")) thisWebApp.Properties["Custom404Path"] = thisWebApp.FileNotFoundPage;
            thisWebApp.Update();

        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }
    }
}
